<!--
  * 分包合同签订
  *
  * @Author:    ccdcc
  * @Date:      2024-07-30 17:17:40
  * @Copyright  njku6jngf
-->
<template>
  <a-modal :title="form.id ? '详情' : '添加'" style="width: 1000px;z-index: 1;" :open="visibleFlag" @cancel="onClose"
    :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-row>
        <a-col :span="12">
          <a-form-item label="合同名称" name="name">
            <a-input style="width: 85%" v-model:value="form.name" placeholder="合同名称" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="合同编号" name="code">
            <a-input style="width: 85%" v-model:value="form.code" placeholder="合同编号" />
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="供应商" name="subcontractorInfoId">
            <a-select style="width: 85%" v-model:value="form.subcontractorInfoId" placeholder="供应商">
              <a-select-option v-for="item in registrantList" :key="item" :value="item.id">{{ item.companyName
                }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="合同签订人" name="employeeIds">
            <a-select style="width: 85%" v-model:value="form.employeeIds" placeholder="合同签订人" :allowClear="true">
              <a-select-option v-for="item in dictValueList" :key="item" :value="item.actualName">
                {{ item.actualName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="合同签订时间" name="concludeSignTime">
            <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.concludeSignTime"
              style="width: 85%" placeholder="合同签订时间" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- ---------- -->
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-row>
        <a-col :span="12">
          <a-form-item label="合同金额" name="contractAmount">
            <a-input-number style="width: 85%" v-model:value="form.contractAmount" placeholder="合同金额" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="采购订单" name="purchaseOrderId">
            <a-tree-select v-model:value="form.purchaseOrderId" style="width: 100%" :tree-data="purchaseOrderIdList"
              tree-checkable allow-clear placeholder="请选择" tree-node-filter-prop="label" @change="checkSelect" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审批人" name="approverId">
            <a-select style="width: 85%" v-model:value="form.approverId" placeholder="审批人" :allowClear="true">
              <a-select-option v-for="item in dictValueList" :key="item" :value="item.employeeId">
                {{ item.actualName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <!-- 查看文件 -->
        <a-col :span="12">
          <a-form-item label="合同文件">
            <a-upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove" maxCount="1">
              <a-button>
                <upload-outlined />
                选择文件
              </a-button>
            </a-upload>
            <a-button v-show="form.id" style="margin-left: 10px" type="primary" size="small"
              @click="viewFile">查看文件</a-button>
          </a-form-item>
          <a-modal :visible="previewVisible" width="800px" :footer="null" @cancel="handleImgCancel">
            <img alt="example" style="width: 100%" :src="previewSrc" />
          </a-modal>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-textarea style="width: 85%" v-model:value="form.remark" placeholder="备注" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-space v-if="!form.id">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
  <a-modal v-model:open="fileopen" title="文件查看" @ok="handleOk" style="width: 1000px; height: 600px;z-index: 2;">
    <div>
      <iframe :src="fileUrl" style="width: 900px; height: 600px"></iframe>
    </div>
  </a-modal>
</template>
<script setup>
import { reactive, ref, nextTick, onMounted } from 'vue';
import _ from 'lodash';
import { message, TreeSelect } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { concludeSignApi } from '/@/api/business/conclude_sign/conclude_sign-api';
import { subcontractorInfoApi } from '/@/api/business/subcontractor-info/subcontractor-info-api';
import { dictApi } from '/src/api/support/dict-api';
import { smartSentry } from '/@/lib/smart-sentry';
import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';
import FileUpload from '/@/components/support/file-upload/index2.vue';
import { fileApi } from '/src/api/support/file-api';

;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const fileList = ref([]);

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};
// 文件
const beforeUpload = (file) => {
  fileList.value = [...(fileList.value || []), file];
  return false;
};
// ------------------------ 事件 ------------------------
// 文件上传

const previewVisible = ref(false);

const previewSrc = ref('');

function handleImgCancel() {
  previewVisible.value = false;
}

// 点击查看文件
const viewFile = async () => {
  fileopen.value = true;
};

const fileUrl = ref('');

const fileopen = ref(false);

const handleOk = (e) => {
  fileopen.value = false;
};

function checkSelect(value, node, extra) {
  const nodeData = extra.triggerNode ? extra.triggerNode.props : null;
  const parentId = nodeData.parentId ? nodeData.parentId : nodeData.value;
  form.purchaseOrderId = parentId;
  form.orderGoodsListIDs = value
  console.log('选中值:', value);
  console.log('父节点ID:', parentId);


}

// 供应商
const registrantList = ref([]);
async function suppliction() {
  let res = await concludeSignApi.SupplierList();
  registrantList.value = res.data;
}
// 合同签订人
const dictValueList = ref([]);

const purchaseOrderIdList = ref([]);

async function queryDict2() {
  let res = await dictApi.getPurchaseOrder();

  if (res.code == 0) {

    for (let i = 0; i < res.data.length; i++) {
      var obj = { children: [], label: res.data[i].projectName, value: res.data[i].id }
      for (let j = 0; j < res.data[i].purchaseOrderGoodsListVOList.length; j++) {
        obj.children.push({ children: [], label: res.data[i].purchaseOrderGoodsListVOList[j].goodsName, value: res.data[i].purchaseOrderGoodsListVOList[j].id,parentId:res.data[i].id })

      }
      purchaseOrderIdList.value.push(obj)
    }


  }

}

async function queryDict() {
  let res = await dictApi.ProjecPersonid();
  dictValueList.value = res.data;
}
const formatSex = (row) => {
  // console.log(row);
  if (!row.sex) {
    return;
  }
  const obj = dictValueList.value.filter((e) => {
    return e.employeeId == row.sex;
  });
  return obj[0].actualName;
};

const emits = defineEmits(['reloadList']);

onMounted(() => {
  queryDict();
  queryDict2();
});
// ------------------------ 显示与隐藏 -------------------
// 是否显示
const visibleFlag = ref(false);

async function show(rowData) {
  fileList.value = []; //file文件清空后再赋值
  if (rowData.fileUrls) {
    var obj = {
      fileKey: rowData.fileUrls,
    };
    var res = await concludeSignApi.getFileUrl(obj);//文件查看的
    if (res.code == 0) {
      fileList.value.push({ name: '合同文件', url: res.data }); //再赋值
      fileUrl.value = res.data;
    }
  }
  suppliction();
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}
// 点击弹框x关闭弹框
function onClose() {
  Object.assign(form, formDefault);
  form.id = null; //是编辑还是添加关闭弹框，清楚表单数据
  visibleFlag.value = false;
}
// ------------------------ 表单 ------------------------
// 组件ref
const formRef = ref();

const formDefault = {
  name: undefined, //合同名称
  code: undefined, //合同编号
  employeeIds: undefined, //合同签订人
  concludeSignTime: undefined, //合同签订时间
  remark: undefined, //备注
  subcontractorInfoId: undefined, //供应商
  contractAmount: undefined, //合同金额
  ContractDocument: undefined, //合同文件
  fileUrls: undefined,
  purchaseOrderId: undefined,
  approverId: undefined,
  approverName:undefined,
  orderGoodsListIDs:[],

  // taskName: undefined, //所属项目
  // projectId: undefined, //项目
  // createTime: undefined, //创建时间
  // updateTime: undefined, //修改时间
};

let form = reactive({ ...formDefault });

const rules = {
  name: [{ required: true, message: '合同名称 必填' }],
  code: [{ required: true, message: '合同编号 必填' }],
  employeeIds: [{ required: true, message: '合同签订人 必填' }],
  concludeSignTime: [{ required: true, message: '合同签订时间 必填' }],
  subcontractorInfoId: [{ required: true, message: '供应商 必填' }],
  contractAmount: [{ required: true, message: '合同金额 必填' }],
  purchaseOrderId: [{ required: true, message: '采购订单 必填' }],
  approverId: [{ required: true, message: '审批人 必填' }],
  fileUrls:[{ required: true, message: '合同文件 必填' }],
  // ContractDocument:[{ required: true, message: '合同文件 必填' }],
  // taskName: [{ required: true, message: '任务名称 必填' }],
  // projectId: [{ required: true, message: '项目 必填' }],
  // createTime: [{ required: true, message: '创建时间 必填' }],
  // updateTime: [{ required: true, message: '修改时间 必填' }],
};

// 点击确定，验证表单
async function onSubmit() {
   let obj = dictValueList.value.filter((e)=>{
    return e.employeeId == form.approverId
   })
   form.approverName=obj[0].actualName
  
  try {
    await formRef.value.validateFields();
    if (form.id) {
      save();
    } else {
      const formData = new FormData();
      formData.append('file', fileList.value[0]);
      let res = await fileApi.uploadFile(formData, FILE_FOLDER_TYPE_ENUM.COMMON.value);
      if (res.code == 0) {
        form.fileUrls = res.data.fileKey;
        save();
      }
    }
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

// 新建、编辑API
async function save() {
  SmartLoading.show();
  try {
    if (form.id) {
      await concludeSignApi.update(form);
    } else {
      await concludeSignApi.add(form);
    }
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}

defineExpose({
  show,
});
</script>
